package ntancnit.app.whereareyou;

import ntancnit.app.database.GetUserName;
import ntancnit.app.firebase.FireBase;
import ntancnit.app.network.Config;
import ntancnit.app.provider.GPSTraker;
import ntancnit.app.servie.AppService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements LocationListener,
		ConnectionCallbacks, OnConnectionFailedListener, OnClickListener {

	private GoogleMap googleMap;
	private LocationClient mLocationClient;
	private Boolean onRecheck = true;
	private String share;
	private Button btnShare;
	private Boolean isShareLayoutApear = false;
	private EditText edtname, edtcontent;
	private TextView tvname;
	private LinearLayout shareLayout;
	private Double myLat = 0.0, myLng = 0.0;
	private MarkerOptions marker;
	private AdView adView;

	private static final LocationRequest REQUEST = LocationRequest.create()
			.setInterval(5000) // 5 seconds
			.setFastestInterval(16) // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_activity);

		share = getIntent().getStringExtra("share");

		try {
			initilizeMap();

		} catch (Exception e) {
			e.printStackTrace();
		}
		checkLocationConnection();

		btnShare = (Button) findViewById(R.id.button1);
		tvname = (TextView) findViewById(R.id.textView3);
		edtname = (EditText) findViewById(R.id.editText2);
		edtcontent = (EditText) findViewById(R.id.editText1);
		shareLayout = (LinearLayout) findViewById(R.id.share_layout);

		btnShare.setOnClickListener(this);
		initShareLayoutApear(isShareLayoutApear);

		Intent myIntent = new Intent(MainActivity.this, AppService.class);
		MainActivity.this.startService(myIntent);

		GetUserName userName = new GetUserName(MainActivity.this);
		tvname.setText(" "+userName.getUserName());
		edtcontent.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (marker != null) {
					if (googleMap != null) {
						googleMap.clear();
						MarkerOptions mkr = new MarkerOptions().position(
								new LatLng(myLat, myLng)).title(
								edtcontent.getText().toString());
						Marker m = googleMap.addMarker(mkr);
						m.showInfoWindow();
					}
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

		});
		
		adView = new AdView(this);
	    adView.setAdSize(AdSize.BANNER);
	    adView.setAdUnitId(Config.AD_UNIT_ID);


	    LinearLayout layout = (LinearLayout) findViewById(R.id.liner);
	    layout.addView(adView);
	    AdRequest adRequest = new AdRequest.Builder()
	        .build();
	    adView.loadAd(adRequest);
	}


	@SuppressLint("NewApi")
	private void initilizeMap() {
		setUpMapIfNeeded();
		setUpLocationClientIfNeeded();
		mLocationClient.connect();
	}

	@SuppressLint("NewApi")
	private void setUpMapIfNeeded() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.mapm)).getMap();
			if (googleMap != null) {
				googleMap.setMyLocationEnabled(true);
			}
		}
	}

	private void setUpLocationClientIfNeeded() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
					this);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		initilizeMap();
		onRecheck = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		mLocationClient.disconnect();
		if (googleMap != null)
			googleMap.setMyLocationEnabled(false);
		onRecheck = true;
	}

	@Override
	public void onLocationChanged(Location arg0) {
		if (googleMap != null) {
			if (onRecheck == true) {
				Location location = new Location(
						mLocationClient.getLastLocation());
				marker = new MarkerOptions().position(new LatLng(location
						.getLatitude(), location.getLongitude()));
				marker.title(share);
				Marker m = googleMap.addMarker(marker);
				m.showInfoWindow();
				CameraPosition cameraPosition = new CameraPosition.Builder()
						.target(new LatLng(location.getLatitude(), location
								.getLongitude())).zoom(15).build();
				myLat = location.getLatitude();
				myLng = location.getLongitude();

				googleMap.animateCamera(CameraUpdateFactory
						.newCameraPosition(cameraPosition));
				googleMap.setMyLocationEnabled(false);
				mLocationClient.disconnect();
				onRecheck = false;
			}
		}
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
	}

	@Override
	public void onConnected(Bundle arg0) {
		mLocationClient.requestLocationUpdates(REQUEST, this);
	}

	@Override
	public void onDisconnected() {

	}

	private void checkLocationConnection() {
		GPSTraker tracker = new GPSTraker(MainActivity.this);
		if (!tracker.canGetLocation()) {
			tracker.showSettingsAlert();
		}
	}

	@Override
	public void onClick(View v) {
		if (v == btnShare) {
			isShareLayoutApear = !isShareLayoutApear;
			initShareLayoutApear(isShareLayoutApear);
			if (isShareLayoutApear) {
				btnShare.setText(getString(R.string.send));
			} else {
				if (isCorrectInput()) {
					initHideSoftKeyboard();
					if (Config.isNetworkAvailable(MainActivity.this)) {
						myShowDialog(getString(R.string.sending));
						sendToFriend(edtname.getText().toString(), edtcontent
								.getText().toString(), String.valueOf(myLat),
								String.valueOf(myLng));
						FireBase.sendToServer("");
					} else {
						myShowDialog(getString(R.string.noInterNetConnection));
					}
				}
				btnShare.setText(getString(R.string.share));
			}

		}
	}

	private void initShareLayoutApear(Boolean flag) {
		if (isShareLayoutApear) {
			shareLayout.setVisibility(View.VISIBLE);
		} else {
			shareLayout.setVisibility(View.GONE);
		}
	}

	private Boolean isCorrectInput() {
		Boolean isCorrect = true;
		GetUserName username = new GetUserName(MainActivity.this);
		if (username.getUserName().equals(edtname.getText().toString())) {
			myShowDialog(getString(R.string.noSentToYourSelf));
			isCorrect = false;
		}
		if (edtname.getText().toString().equals(tvname.getText())) {
			myShowDialog(getString(R.string.inCorrectName));
			isCorrect = false;
		}
		String txname = edtname.getText().toString().replaceAll(" ", "");
		String txcontent = edtcontent.getText().toString().replaceAll(" ", "");
		if (txname.equals("") || txcontent.equals("")) {
			myShowDialog(getString(R.string.inCorrectInput));
			isCorrect = false;
		}
		return isCorrect;
	}

	private void myShowDialog(String content) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				MainActivity.this);
		alertDialogBuilder.setTitle(getString(R.string.notify));
		alertDialogBuilder
				.setMessage(content)
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
							}
						});
		AlertDialog alertDialog = alertDialogBuilder.create();

		alertDialog.show();
	}

	private void sendToFriend(String name, String content, String lat,
			String lng) {
		GetUserName userName = new GetUserName(MainActivity.this);
		String sendContent = userName.getUserName()
				+ getString(R.string.sendCharacter) + name
				+ getString(R.string.sendCharacter) + content
				+ getString(R.string.sendCharacter) + lat
				+ getString(R.string.sendCharacter) + lng;
		FireBase.sendToServer(sendContent);
	}

	public void initHideSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(MainActivity.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edtcontent.getWindowToken(), 0);
	}
}
